package top.kiterunner.learning.concurrency_test.ContainerDemo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * AdorynZhao in Tencent-UESTC.
 * Source Code Created on 2017/7/6.
 */
public class WatchContainerDemo1 {

    private volatile List<Item> itemList = new ArrayList<>();

    public void add(Item item) {
        this.itemList.add(item);
    }

    public int size() {
        return this.itemList.size();
    }

    public void produce() {
        for (int i = 0; i < 10; i++) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.add(new Item());
            System.out.println("Adding " + i + " Item...");
        }
    }

    public void watch() {
        while (true) {
            if (this.size() == 5) {
                System.out.println(Thread.currentThread().getName() + " Watch Over.");
                break;
            }
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        WatchContainerDemo1 wcd1 = new WatchContainerDemo1();

        Thread thread1 = new Thread(wcd1::produce, "Thread_1");
        Thread thread2 = new Thread(wcd1::watch, "Thread_2");

        try {
            thread1.start();
            thread2.start();
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public class Item {

        public Item() {}
    }
}
